#ifndef CHATSERVICE_H
#define CHATSERVICE_H
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <unordered_map>
#include <mutex>
#include "json.hpp"
#include "usermodel.h"
#include "offlinemessagemodel.h"
#include "friendmodel.h"
#include "groupmodel.h"
#include"redis.h"
using namespace std;
using namespace muduo::net;
using namespace muduo;
using json = nlohmann::json;

// 处理消息的事件回调函数
using MsgHandler = std::function<void(const TcpConnectionPtr &, json &, Timestamp)>;
class ChatService
{
public:
    void login(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void loginout(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void reg(const TcpConnectionPtr &conn, json &js, Timestamp time);

    // 一对一聊天事件
    void oneChat(const TcpConnectionPtr &conn, json &js, Timestamp time);

    void addFriend(const TcpConnectionPtr &conn, json &js, Timestamp time);

    void createGroup(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void addGroup(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void groupChat(const TcpConnectionPtr &conn, json &js, Timestamp time);

    static ChatService *getInstance();

    MsgHandler getHandler(int msgid);

    void clientCloseException(const TcpConnectionPtr &conn);

    // 服务器重置方法
    void reset();

    void handlerRedisSubscribeMessage(int userid, string msg);

private:
    // 定义多用户连接的map记录的互斥锁，线程安全
    mutex _connMutex;

    ChatService();

    // 存储事件的处理机制，判断是注册还是登录事件
    unordered_map<int, MsgHandler> _msgHandlerMap;
    // 存储在线用户的连接情况
    unordered_map<int, TcpConnectionPtr> _userConnMap;

    UserModel _userModel;
    OfflineMessageModel _offlineMessgeModel;
    FriendModel _friendModel;
    GroupModel _groupmodel;

    Redis _redis;
};
#endif